package org.example.Dao;

import org.example.entity.Option;
import org.example.utils.DruidUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class OptionDao {

    /**
     * 添加选项
     *
     * @param tid     题目id
     * @param options 选项列表
     * @return 影响的行数
     * @throws Exception 数据库异常
     */
    public int addOptions(int tid, List<Option> options) throws Exception {
        String sql = "INSERT INTO `option` (tid, url, name) VALUES (?, ?, ?)";
        Connection connection = DruidUtil.getConnection();
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        for (Option option : options) {
            preparedStatement.setInt(1, tid);
            preparedStatement.setString(2, option.getUrl());
            preparedStatement.setString(3, option.getName());
            preparedStatement.addBatch();


        }
        int[] result = preparedStatement.executeBatch();
        return result.length;

    }

    /**
     * 获取选项
     *
     * @param tid 题目id
     * @return 选项列表
     * @throws Exception 数据库异常
     */
    public List<Option> getOptions(int tid) throws Exception {
        String sql = "SELECT * FROM `option` WHERE tid = ?";
        Connection connection = DruidUtil.getConnection();
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setInt(1, tid);
        ResultSet resultSet = preparedStatement.executeQuery();
        List<Option> options = new ArrayList<>();
        while (resultSet.next()) {
            Option option = new Option();
            option.setOid(resultSet.getInt("oid"));
            option.setTid(resultSet.getInt("tid"));
            option.setUrl(resultSet.getString("url"));
            option.setName(resultSet.getString("name"));
            options.add(option);
        }
        return options;
    }
}
